package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.util.*;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.adapter.AssessTableAdapter;
import com.ruoyi.system.domain.Assess;
import com.ruoyi.system.domain.OptionCard;
import com.ruoyi.system.domain.TaskLevel;
import com.ruoyi.system.domain.dto.AssessTableDTO;
import com.ruoyi.system.domain.dto.AssessTableListDTO;
import com.ruoyi.system.domain.dto.QuestionReqDTO;
import com.ruoyi.system.mapper.AssessMapper;
import com.ruoyi.system.service.ISysRoleService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AssessTableMapper;
import com.ruoyi.system.domain.AssessTable;
import com.ruoyi.system.service.IAssessTableService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-22
 */
@Service
public class AssessTableServiceImpl implements IAssessTableService {
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private AssessTableMapper assessTableMapper;
    @Autowired
    private AssessMapper assessMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public AssessTable selectAssessTableById(Long id) {
        return assessTableMapper.selectAssessTableById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param assessTable 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<AssessTable> selectAssessTableList(AssessTable assessTable) {
        return assessTableMapper.selectAssessTableList(assessTable);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param assessTable 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertAssessTable(AssessTable assessTable) {
        return assessTableMapper.insertAssessTable(assessTable);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param assessTable 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateAssessTable(AssessTable assessTable) {
        return assessTableMapper.updateAssessTable(assessTable);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAssessTableByIds(Long[] ids) {
        return assessTableMapper.deleteAssessTableByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAssessTableById(Long id) {
        return assessTableMapper.deleteAssessTableById(id);
    }

    @Override
    @Transactional
    public boolean saveOrUpdateBatch(List<AssessTable> assessTables) {
        for (AssessTable assessTable : assessTables) {
            if (assessTable.getId() != null && assessTable.getId() > 0L) {
                assessTableMapper.updateAssessTable(assessTable);
            } else {
                assessTableMapper.insertAssessTable(assessTable);
            }
        }
        return true;
    }

    @Override
    public void importTable(MultipartFile file, LoginUser loginUser) {
        if (file.isEmpty()) {
            throw new ServiceException("文件内容为空");
        }
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet baseInfoSheet = workbook.getSheet("基本属性"); // 我们处理第一个工作表
            Iterator<Row> baseInfoRowIterator = baseInfoSheet.iterator();

            Sheet assessGradeSheet = workbook.getSheet("评测等级"); // 我们处理第二个工作表
            Iterator<Row> assessGradeRowIterator = assessGradeSheet.iterator();

            Sheet questionAndOptionSheet = workbook.getSheet("问题和选项"); // 我们处理第三个工作表
            Iterator<Row> questionAndOptionRowIterator = questionAndOptionSheet.iterator();

            // 跳过标题行（如果需要）
            if (baseInfoRowIterator.hasNext()) {
                baseInfoRowIterator.next();
            }

            if (assessGradeRowIterator.hasNext()) {
                assessGradeRowIterator.next();
            }

            if (questionAndOptionRowIterator.hasNext()) {
                questionAndOptionRowIterator.next();
            }

            Map<String, AssessTableDTO> assessTableMap = new HashMap<>();

            //处理基本属性表
            while (baseInfoRowIterator.hasNext()) {
                Row row = baseInfoRowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                boolean isEmptyRow = false;
                AssessTableDTO assessTableDo = new AssessTableDTO();
                String cellValue1 = null;
                assessTableDo.setTableCreator("");

                int cellIndex = 0;
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    String cellValue = getCellValueAsString(cell);

                    switch (cellIndex) {
                        case 0:
                            if (StringUtils.isEmpty(cellValue)) {
                                isEmptyRow = true;
                                break;
                            }
                            cellValue1 = cellValue;
                            assessTableDo.setName(cellValue);
                            break;
                        case 1:
                            assessTableDo.setEvaluation(cellValue);
                            break;
                        case 2:
                            assessTableDo.setShortName(cellValue);
                            break;
                        case 3:
                            assessTableDo.setIntroduce(cellValue);
                            break;
                        case 4:
                            assessTableDo.setNumber(cellValue);
                            break;
                        case 5:
                            assessTableDo.setPointsType(cellValue.equals("总分") ? 1L : 0L);
                            break;
                        // 添加更多字段的case语句
                    }

                    if (isEmptyRow) {
                        System.out.println("Found an empty row. Stopping traversal.");
                        break;
                    }
                    cellIndex++;
                }
                if (isEmptyRow) {
                    System.out.println("Found an empty row. Stopping traversal.");
                    break;
                }
                assessTableMap.put(cellValue1, assessTableDo);
            }


            // 处理测评等级表
            while (assessGradeRowIterator.hasNext()) {
                Row row = assessGradeRowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                boolean isEmptyRow = false;
                AssessTableDTO assessTableDo = new AssessTableDTO();

                TaskLevel taskLevel = new TaskLevel();
                int cellIndex = 0;
                String cellValue1 = null;
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    String cellValue = getCellValueAsString(cell);

                    switch (cellIndex) {
                        case 0:
                            if (StringUtils.isEmpty(cellValue)) {
                                isEmptyRow = true;
                                break;
                            }
                            cellValue1 = cellValue;
                            if (assessTableMap.containsKey(cellValue)) {
                                assessTableDo = assessTableMap.get(cellValue);
                            }
                            break;
                        case 1:
                            taskLevel.setName(cellValue);
                            break;
                        case 2:
                            taskLevel.setDetail(cellValue);
                            break;
                        case 3:
                            taskLevel.setLevel(cellValue);
                            break;
                        case 4:
                            taskLevel.setLowestScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 5:
                            taskLevel.setIsLowestScore(cellValue.equals("是"));
                            break;
                    }
                    if (isEmptyRow) {
                        System.out.println("Found an empty row. Stopping traversal.");
                        break;
                    }
                    cellIndex++;
                }
                if (isEmptyRow) {
                    System.out.println("Found an empty row. Stopping traversal.");
                    break;
                }
                List<TaskLevel> taskLevelList = assessTableDo.getTaskLevel();
                if (CollectionUtils.isEmpty(taskLevelList)) {
                    taskLevelList = new ArrayList<>();
                    taskLevelList.add(taskLevel);
                } else {
                    taskLevelList.add(taskLevel);
                }
                assessTableDo.setTaskLevel(taskLevelList);
                assessTableMap.merge(cellValue1, assessTableDo, (oldValue, newValue) -> newValue);
            }


            // 处理问题选项表
            while (questionAndOptionRowIterator.hasNext()) {
                Row row = questionAndOptionRowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                boolean isEmptyRow = false;
                AssessTableDTO assessTableDo = new AssessTableDTO();

                QuestionReqDTO questionReqDTO = new QuestionReqDTO();
                int cellIndex = 0;

                OptionCard optionCard1 = new OptionCard();
                OptionCard optionCard2 = new OptionCard();
                OptionCard optionCard3 = new OptionCard();
                OptionCard optionCard4 = new OptionCard();
                OptionCard optionCard5 = new OptionCard();
                OptionCard optionCard6 = new OptionCard();
                OptionCard optionCard7 = new OptionCard();
                OptionCard optionCard8 = new OptionCard();
                List<OptionCard> optionCardList = new ArrayList<>();
                String cellValue1 = null;
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    String cellValue = getCellValueAsString(cell);

                    switch (cellIndex) {
                        case 0:
                            if (StringUtils.isEmpty(cellValue)) {
                                System.out.println(cellIndex + "-------dsadasf");
                                isEmptyRow = true;
                                break;
                            }
                            cellValue1 = cellValue;
                            if (assessTableMap.containsKey(cellValue)) {
                                assessTableDo = assessTableMap.get(cellValue);
                            }
                            break;
                        case 2:
                            questionReqDTO.setName(cellValue);
                            break;
                        case 4:
                            optionCard1.setName(cellValue);
                            break;
                        case 5:
                            optionCard1.setScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 6:
                            optionCard2.setName(cellValue);
                            break;
                        case 7:
                            optionCard2.setScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 8:
                            optionCard3.setName(cellValue);
                            break;
                        case 9:
                            optionCard3.setScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 10:
                            optionCard4.setName(cellValue);
                            break;
                        case 11:
                            optionCard4.setScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 12:
                            optionCard5.setName(cellValue);
                            break;
                        case 13:
                            optionCard5.setScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 14:
                            optionCard6.setName(cellValue);
                            break;
                        case 15:
                            optionCard6.setScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 16:
                            optionCard7.setName(cellValue);
                            break;
                        case 17:
                            optionCard7.setScore(Double.valueOf(cellValue).longValue());
                            break;
                        case 18:
                            optionCard8.setName(cellValue);
                            break;
                        case 19:
                            optionCard8.setScore(Double.valueOf(cellValue).longValue());
                            break;
                    }
                    if (isEmptyRow) {
                        System.out.println("Found an empty row. Stopping traversal.");
                        break;
                    }
                    cellIndex++;
                }
                if (isEmptyRow) {
                    System.out.println("Found an empty row. Stopping traversal.");
                    break;
                }
                List<QuestionReqDTO> questionReqDTOList = assessTableDo.getQuestions();
                if (CollectionUtils.isEmpty(questionReqDTOList)) {
                    questionReqDTOList = new ArrayList<>();
                    optionCardList.add(optionCard1);
                    optionCardList.add(optionCard2);
                    optionCardList.add(optionCard3);
                    optionCardList.add(optionCard4);
                    optionCardList.add(optionCard5);
                    optionCardList.add(optionCard6);
                    optionCardList.add(optionCard7);
                    optionCardList.add(optionCard8);
                    questionReqDTO.setOptions(optionCardList);

                    questionReqDTOList.add(questionReqDTO);
                } else {
                    optionCardList.add(optionCard1);
                    optionCardList.add(optionCard2);
                    optionCardList.add(optionCard3);
                    optionCardList.add(optionCard4);
                    optionCardList.add(optionCard5);
                    optionCardList.add(optionCard6);
                    optionCardList.add(optionCard7);
                    optionCardList.add(optionCard8);
                    questionReqDTO.setOptions(optionCardList);

                    questionReqDTOList.add(questionReqDTO);
                }
                assessTableDo.setQuestions(questionReqDTOList);
                List<SysRole> sysRoles = roleService.selectRoleByUserId(loginUser.getUserId());
                if (!sysRoles.isEmpty()) {
                    assessTableDo.setRoleId(sysRoles.get(0).getRoleId());
                } else {
                    throw new ServiceException("未找到用户[" + loginUser.getUsername() + "]的角色");
                }
                assessTableDo.setAdminType(0);
                if (loginUser.getUser().isAdmin()) {
                    assessTableDo.setAdminType(1);
                }
                assessTableMap.merge(cellValue1, assessTableDo, (oldValue, newValue) -> newValue);
            }

            List<AssessTable> assessTables = AssessTableAdapter.adapter(assessTableMap);
            this.saveOrUpdateBatch(assessTables);
        } catch (IOException e) {
            throw new ServiceException("导入失败，异常" + e.getMessage());
        }
    }

    @Override
    public List<AssessTable> selectAssessTableQueryList(AssessTableListDTO assessTable) {
        if (assessTable.getTaskId() != null) {
            Assess assess = assessMapper.selectAssessById(assessTable.getTaskId());
            int status = determineTaskStatus(assess);
            if (status == 0) {
                throw new ServiceException("任务于：" + assess.getStartTime() + "开始，请耐心等待");
            } else if (status == 2) {
                throw new ServiceException("任务于：" + assess.getEndTime() + "已结束");
            }
        }
        if (StringUtils.isNotEmpty(assessTable.getScaleIdList())) {
            String[] s = assessTable.getScaleIdList().split(",");
            List<Long> ids = new ArrayList<>();
            for (String str : s) {
                ids.add(Long.parseLong(str));
            }
            assessTable.setScaleIdArray(ids);
        }
        return assessTableMapper.selectAssessTableQueryList(assessTable);
    }

    // 辅助方法，用于将Cell转换为字符串
    private String getCellValueAsString(Cell cell) {
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }

    private int determineTaskStatus(Assess assess) {
        Date now = new Date();
        Date startTime = DateUtils.parseDate(assess.getStartTime());
        Date endTime = DateUtils.parseDate(assess.getEndTime());

        if (now.before(startTime)) {
            return 0; // 未开始
        } else if (now.after(endTime)) {
            return 2; // 已完成
        } else {
            return 1; // 进行中
        }
    }
}
